﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class bl_default : System.Web.UI.Page
{
    public int CurrentPage
    {
        get
        {
            // look for current page in ViewState
            object o = this.ViewState["_CurrentPage"];
            if (o == null)
                return 0; // default page index of 0
            else
                return (int)o;
        }
        set
        {
            this.ViewState["_CurrentPage"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ItemsGet();
    }
    private void ItemsGet()
    {
        string tag = Request.QueryString["category"];
        var ba = new DataBase.BlogAdapter();

        PagedDataSource pagedDS = new PagedDataSource();
        pagedDS.AllowPaging = true;
        pagedDS.PageSize = 3;

        if (String.IsNullOrEmpty(tag))
        {
            pagedDS.DataSource = ba.GetArticles(null, null).ToList();
        }
        else
        {
            var t = new DataBase.Tag() { TagName = tag };
            var tec = new DataBase.TagEqualityComparer();
            pagedDS.DataSource = ba.GetArticles(null, null).Where(a => a.Tags.Contains(t, tec)).ToList();
        }

        pagedDS.CurrentPageIndex = CurrentPage;
        lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + pagedDS.PageCount.ToString();
        // Disable Prev or Next buttons if necessary
        cmdPrev.Enabled = !pagedDS.IsFirstPage;
        cmdNext.Enabled = !pagedDS.IsLastPage;

        Posts.DataSource = pagedDS;
        Posts.DataBind();
    }
    protected string SetTagsHtml(object tags)
    {
        var Tags = (System.Data.Objects.DataClasses.EntityCollection<DataBase.Tag>)tags;
        string PostTags = "";
        foreach (var tg in Tags)
        {
            PostTags += "<a rel=\"category tag\" title=\"View all posts in " + tg.TagName + "\" href=\"" + Master.Root + "default.aspx?category=" + tg.TagName + "\">" + tg.TagName + "</a>, ";
        }
        return PostTags;
    }
    protected void nextClick(object sender, EventArgs e)
    {
        CurrentPage += 1;
        ItemsGet();
    }
    protected void prevClick(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        ItemsGet();
    }
}